const app = getApp();
const publicFun = require('/utils/public.js');
import { modifyUserName } from '/utils/request'
Page({
  data: {
    userData: {}
  },
  onLoad(options) {
    let data = {
      Url: options.Url,
      UserName: options.UserName,
      Phone: options.Phone
    }
    this.setData({
      userData: data,
      systemInfo: app.globalData.systemInfo
    });
    my.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff',
    })
  },
  modifyUserHeader() {
    my.chooseImage({
      chooseImage: 1,
      sourceType: ['camera','album'],
      count: 1,
      success: (res) => {
        my.compressImage({
          apFilePaths: res.apFilePaths,
          compressLevel: 1,
          success: data => {
            this.uploadImg(data.apFilePaths[0])
          }
        })
      },
    })
  },
  uploadImg(path) {
    my.showLoading();
    var params = {};
    let uploads = [publicFun.commonUpLoadImg(publicFun.api.modifyUserHead, path, params)];
    Promise.all(uploads).then(res => {
      my.hideLoading();
      let data = res[0];
      if(data.IsSuccess == 1){
        app.getUserData();
        publicFun.showToast(data.Message);
        setTimeout(() => {
          my.reLaunch({
            url: '/pages/my/my'
          });  
        }, 1500)
      }else{
        publicFun.showToast(data.Message);
      }
    }).catch(() => {
      my.hideLoading();
      publicFun.showToast("修改失败")
    });
  },

  modifyUserName() {
    my.prompt({
      title: '输入昵称',
      message: ' ',
      placeholder: this.data.userData.UserName,
      okButtonText: '确定',
      cancelButtonText: '取消',
      complete: (result) => {
        if(result.ok == true){
          let params = {
            UserId: app.globalData.userid,
            Name: result.inputValue ? result.inputValue : this.data.userData.UserName
          }
          my.showLoading();
          this.modifyUserUserName(params)
        }
      },
    });
  },
  async modifyUserUserName(params) {
    try {
      const res = await modifyUserName(params);
      my.hideLoading();
      if(res.S == 1){
        my.switchTab({
          url: '/pages/my/my'
        }); 
      }else{
        publicFun.showToast(res.M ? res.M : '加载失败');
      }
    } catch (e) {
      my.hideLoading();
      publicFun.showToast('失败，请稍后再试')
    }
  }
});
